const express = require('express')
const router = express.Router()
const { main } = require('../DB/index')
const multer = require('multer')
const path = require('path')
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'public')
  },
  filename: function (req, file, cb) {
    const suffix = path.extname(file.originalname)
    cb(null, `${new Date().getTime()}-${Math.random().toString().slice(2)}${suffix}`)
  }
})
const imgupLoad = multer({ storage })

// 
router.get('/navIcon', async function (req, res) {
  let sql = 'select * from navIcon'
  try {
        result = await main(sql)
      } catch (e) {
        result = []
      }
      res.json(result)
})
//上传图片
router.post('/editIcon', imgupLoad.single('img'), async function (req, res) {
  console.log(req.file)
  let url = 'http://localhost:8888/' + req.file.filename
  let sql = `insert into navIcon (img) values ('${url}')`
  try {
    result = await main(sql)
  } catch (e) {
    result = []
  }
  res.json(result)
})

router.get('/getNewIcon', async function (req, res) {
  let { id } = req.query
  let sql2 = `select * from navIcon where id = ${id}`
  try {
    result = await main(sql2)
  } catch (e) {
    result = []
  }
  res.json(result)
})

module.exports = router